package cn.zbmao.web.dao.impl;

import cn.zbmao.web.bean.Constants;
import cn.zbmao.web.dao.SuccessfulNewsForUserDao;
import cn.zbmao.web.entity.TenderNews;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: huangzheng
 * Date: 2014/11/4
 * Time: 11:30
 *
 * To change this template use File | Settings | File Templates.
 */
public class SuccessfulNewsForUserDaoImpl implements SuccessfulNewsForUserDao {
    private static final Logger LOGGER = Logger.getLogger(SuccessfulNewsForUserDaoImpl.class);

    /**
     *参数 List<TenderNews> 招标信息列表 userId 用户Id
     * 将用户Id与其关联的招标存入到successful_news_for_user 表中
     * 当中标公司为空或者为采购中心时，数据不存入，
     * */
    @Override
    public void save(List<TenderNews> newsList, int userId) {

        List<TenderNews> record= new ArrayList<TenderNews>();

            for(TenderNews newslist:newsList){
                Record tendernews=new Record();
                tendernews.set("user_id",userId);
                tendernews.set("tender_news_id", newslist.getInfoId());
                tendernews.set("tender_id", newslist.getTenderId());
//                当中标公司为空或者中标公司时采购中心时，跳过该次循环，不将数据插入successful_news_for_user 表中
                if (StringUtils.isBlank(newslist.getWinBidCompany())||newslist.getWinBidCompany().endsWith("采购中心")){
                    continue;
                }
                tendernews.set("win_bid_company",newslist.getWinBidCompany());
//                if (StringUtils.isBlank(newslist.getWinBidFigure())){
//                    continue;
//                }
                tendernews.set("win_bid_figure",newslist.getWinBidFigure());

                try {
                    Db.save("successful_news_for_user", tendernews);
                } catch  (ActiveRecordException e){
                    //LOGGER.error("ActiveRecordException");
                }
            }


    }

    @Override
    public void update(List<TenderNews> newsList, int userId) {

    }

    /**
     *参数 userId
     * 通过userId查出successful_news_for_user招标编号，中标公司，中标金额，
     * 并以List<TenderNews>返回
     * */
    @Override
    public List<TenderNews> getAllNewsListForUserId(Integer userId) {
        List<TenderNews> tendernews =new ArrayList<TenderNews>();
        List<Record> record= Db.find("select tender_id,win_bid_company,win_bid_figure from " + Constants.SUCCESSFUL_NEWS_FON_USER + " where user_id=?", userId);
       //遍历List<Record> 将数据存入TenderNews中                                                                            //successful_news_for_user
        for (Record records:record){
            TenderNews tn=new TenderNews();
            tn.setTenderId(records.getStr("tender_id"));
            tn.setWinBidCompany(records.getStr("win_bid_company"));
            tn.setWinBidFigure(records.getDouble("win_bid_figure"));
            tendernews.add(tn);
        }
        return tendernews;
    }

    /**
     * 参数 userId
     * 通过userId删除successful_news_for_user 表中对应的数据
     * */
    @Override
    public void delete(Integer userId) {

        Db.update("delete from " + Constants.SUCCESSFUL_NEWS_FON_USER + " where user_id=?", userId);
                                //successful_news_for_user
    }

    /**
     * 参数 userId:用户Id  num：去除数据条数  orderBy: 判断按num中标次数或者figure金额排序
     * 按照中标公司分组 通过userId查出 successful_news_for_user表中 公司名称，中标总金额，中标总次数
     * 并按照金额或次数排序
     *
     * */
    @Override
    public List<Map<String, Object>> getSuccessfulForUser(int userId, int num, int orderBy) {

        StringBuffer sb=new StringBuffer();
        sb.append("select COUNT(id) as num,win_bid_company,sum(win_bid_figure) as figure from successful_news_for_user where  win_bid_company != '' and user_id=?");
                                                                                                //successful_news_for_user
        sb.append(" GROUP BY win_bid_company ORDER BY ");
//        为0时按照中标数量排序，为1时按照中标金额排序
        if(orderBy==0){
            sb.append("num");
        }else{
            sb.append("figure");
        }
        sb.append(" desc limit ?");


        List<Record> recordList = Db.find(sb.toString(), new Object[]{userId, num});

        List<Map<String,Object>> newsList = new ArrayList<Map<String, Object>>();

        for(Record record:recordList){
            newsList.add(record.getColumns());
        }
        return newsList;
    }
}
